package modules.arc.service.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import luxing.common.service.impl.CommonServiceImpl;
import luxing.util.LoginUserUtil;
import modules.arc.entity.ArcExt;
import modules.arc.entity.Driver;
import modules.arc.entity.DriverExt;
import modules.arc.service.DriverService;

/**
 * 
 * @author zzc
 *
 */
@Service("driverService")
@Transactional
public class DriverServiceImpl extends CommonServiceImpl implements DriverService {

	public void save(Driver driver, List<ArcExt> arcExtList, HttpServletRequest request) {
		// 保存司机
		save(driver);
		// 保存司机扩展信息
		for (ArcExt arcExt : arcExtList) {
			String value = request.getParameter(arcExt.getId());
			if (StringUtils.isNotBlank(value)) {
				DriverExt driverExt = new DriverExt();
				driverExt.setDriverId(driver.getId());
				driverExt.setArcExtId(arcExt.getId());
				driverExt.setValue(value);
				save(driverExt);
			}
		}
	}

	public void update(Driver driver, List<DriverExt> driverExtList) {
		// 司机
		saveOrUpdate(driver);
		// 扩展属性,先删除再重新增加
		String hql = "delete from DriverExt where driverId=?";
		executeHql(hql, driver.getId());
		for (DriverExt driverExt : driverExtList) {
			save(driverExt);
		}
	}

	public void delete(Driver driver) {
		// TODO
		// 删除扩展信息
		String extHql = "delete from DriverExt where driverId=?";
		executeHql(extHql, driver.getId());
		// 删除司机
		super.delete(driver);
	}

	public Driver getByName(String name) {
		String hql = "from Driver where name=? and tenantId=?";
		List<Driver> list = listByHql(hql, name, LoginUserUtil.getLoginUser().getTenantId());
		if (CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	public Driver getByPhone(String phone) {
		String hql = "from Driver where phone=? and tenantId=?";
		List<Driver> list = listByHql(hql, phone, LoginUserUtil.getLoginUser().getTenantId());
		if (CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	public Driver getByIdCard(String idCard) {
		String hql = "from Driver where idCard=? and tenantId=?";
		List<Driver> list = listByHql(hql, idCard, LoginUserUtil.getLoginUser().getTenantId());
		if (CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

}
